<?php
/**
 * Created by PhpStorm.
 * User: boye009
 * Date: 2016/4/20
 * Time: 14:04
 */

namespace Shop\Api;

use Common\Api\Api;
use Shop\Model\ProductQuantityHisModel;
use Shop\Model\ProductSkuModel;

class ProductQuantityHisApi extends Api{

    /**
     * 添加
     */
    const ADD = "Shop/ProductQuantityHis/add";
    /**
     * 批量添加
     */
    const ADD_ALL = "Shop/ProductQuantityHis/addAll";
    /**
     * 保存
     */
    const SAVE = "Shop/ProductQuantityHis/save";
    /**
     * 查询一条数据
     */
    const GET_INFO = "Shop/ProductQuantityHis/getInfo";

    /**
     * 查询，不分页
     */
    const QUERY_NO_PAGING = "Shop/ProductQuantityHis/queryNoPaging";

    /**
     * 查询，不分页
     */
    const QUERY = "Shop/ProductQuantityHis/query";

    protected function _init(){
        $this -> model = new ProductQuantityHisModel();
    }

    public function addAll($entity){
        $len = count($entity);//数据个数
        if($len == 0){
            $this -> apiReturnSuc("库存变动成功");
        }
        $skuModel = new ProductSkuModel();
        $skuModel -> startTrans();//开启事务
        $error = false;
        //$sku_entity = array();
        foreach($entity as $k => $v){
            $pid = $v['pid'];
            $sku_id = $v['sku_id'];
            $left_quantity = $v['left_quantity'];
            $map = array(
                'product_id' => $pid,
                'sku_id' => $sku_id,
            );
            $sku_entity = array(
                'quantity' => $left_quantity,
            );
            $result = $skuModel -> create($sku_entity,2);
            if($result === false){
                $error = $skuModel -> getError();
            }
            if($error === false){
                $result = $skuModel -> where($map) -> save();
            }
            if($result === false){
                $error = $skuModel -> getDbError();
            }
            if($error !== false){
                break;
            }
        }
        if($error === false){
            if($len == 1){
                $result = $this -> model -> create($entity[0],1);
                if($result === false){
                    $error = $this -> model -> getError();
                }
                if($error === false){
                    $result = $this -> model -> add();
                }
                if($result === false){
                    $error = $this -> model -> getDbError();
                }
            }else{
                $result = $this -> model -> addAll($entity);
                if($result === false){
                    $error = $this -> model -> getDbError();
                }
            }
        }
        if($error === false){
            $skuModel -> commit();
            return $this -> apiReturnSuc("库存变动成功");
        }else{
            $skuModel -> rollback();
            return $this -> apiReturnErr($error);
        }
    }




}